import React, { useEffect, useState } from 'react';
import { Button, Form, message, Modal, Select, Switch } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
import { DownOutlined } from '#/utils/antdIcons.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { BaseSelect, PersonModal } from '../index';
import type { TABS_LIST } from '../../dictionary';
import { CHECKTIME_OPTIONS, REMINDER_TYPE_LIST } from '../../dictionary';
import type { ISearchFormData } from '../../type';
import { batchSetRemindH } from '../../service';
import styles from './index.less';

interface IProps {
  /**
   * 是否是编辑状态
   */
  isEdit?: boolean;
  /**
   * 搜索条件
   */
  onPress: (data: Record<string, any>) => void;
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 表单值
   */
  value: any;
  /**
   * 刷新基础数据
   */
  getSearchFormData: () => void;
  /**
   * 当前Tabs activeKey
   */
  activeKey: TABS_LIST;
  /**
   * 选择的当前月份
   */
  checkedDate: any;
}

const SetRemindersComponent = (props: IProps) => {
  const [form] = Form.useForm();
  const {
    onPress,
    searchFormData,
    value: _value,
    isEdit = false,
    getSearchFormData,
    checkedDate,
    activeKey,
    marketId,
  } = props;
  const { creatorOptions } = searchFormData;
  const [visible, setVisible] = useState<boolean>(true);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [value, setValue] = useState<any>(_value);
  const [reminderData, setReminderData] = useState<any>(_value?.reminderList);
  const [remindFlag, setValid] = useState<string>('1');

  useEffect(() => {
    const reminderList = _value?.reminderList
      ? _value?.reminderList?.map((item: any) => item.userId)
      : [];
    form &&
      form.setFieldsValue({
        ..._value,
        reminderList,
        remindFlag: _value?.remindFlag ? _value?.remindFlag : '1',
      });
    setValue({
      ..._value,
      reminderList,
      remindFlag: _value?.remindFlag ? _value?.remindFlag : '1',
    });
    setReminderData(_value?.reminderList);
    setValid(_value?.remindFlag ? _value?.remindFlag : '1');
  }, [searchFormData, _value]);

  // 确定按钮
  const _onOk = async () => {
    form &&
      form.validateFields().then(async (values) => {
        if (isEdit) {
          setIsLoading(true);
          let res: any = {};
          res = await batchSetRemindH({
            ...values,
            reminderTime: values?.reminderTime,
            id: value?.id,
            remindFlag,
          });

          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.info('提醒设置成功！');
            onPress({ index: 1, data: { ...values, reminderList: reminderData, remindFlag } });
            setVisible(false);
          } else {
            message.info(res?.message || '提醒设置失败！');
          }
          setIsLoading(false);
        } else {
          onPress({ index: 1, data: { ...values, reminderList: reminderData, remindFlag } });
          setVisible(false);
        }
      });
  };

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 设置提醒对象弹框
  const handelCreatorElement = async () => {
    const res: any = await PersonModal.show({
      searchFormData,
      value: value?.reminderList || [],
      checkedDate,
      tabActiveKey: activeKey,
      getSearchFormData,
      marketId,
    });
    if (res.index === 1) {
      const values = form && form.getFieldsValue();
      setReminderData(res?.reminderData);
      setValue({ ...value, ...values, reminderList: res.reminderList });
      form && form.setFieldsValue({ ...values, reminderList: res.reminderList });
    }
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={_onOk} loading={isLoading}>
      提交
    </Button>,
  ];

  return (
    <Modal
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />

          <span className={styles.title}> 提醒设置 </span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="todo"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="remindFlag"
            label="提醒启用"
            rules={[{ required: true, message: '请选择提醒启用' }]}
          >
            <Switch
              checked={remindFlag === '1'}
              onChange={(e) => {
                setValid(e ? '1' : '0');
              }}
            />
          </Form.Item>
          <Form.Item
            name="reminderTime"
            label="提醒时间"
            rules={[{ required: true, message: '请选择提醒时间' }]}
          >
            <BaseSelect
              options={CHECKTIME_OPTIONS}
              maxTagCount={1}
              maxTagTextLength={1}
              showArrow={true}
              logo={<DownOutlined />}
              placeholder={'提醒时间'}
              isShowSelectAll={false}
            />
          </Form.Item>
          <Form.Item
            name="reminderType"
            label="提醒方式"
            rules={[{ required: true, message: '请选择提醒方式' }]}
          >
            <Select placeholder={'提醒方式'} showArrow={true} options={REMINDER_TYPE_LIST} />
          </Form.Item>
          <Form.Item
            name="reminderList"
            label="提醒对象"
            rules={[{ required: true, message: '请选择提醒对象' }]}
          >
            <Select
              placeholder={'提醒对象'}
              showArrow={true}
              open={false}
              onClick={handelCreatorElement}
              mode="multiple"
              maxTagTextLength={1}
              maxTagCount={1}
              options={creatorOptions as any[]}
            />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

class SetRemindersModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <SetRemindersComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new SetRemindersModal();
